package com.groot.medical.servlet;

import java.io.IOException;
import java.nio.charset.Charset;
import java.sql.Timestamp;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import com.google.gson.Gson;
import com.groot.common.controller.BaseServletController;
import com.groot.common.util.SimpleDateUtil;
import com.groot.common.util.TicketUtil;
import com.groot.medical.entity.ChronicDisease;
import com.groot.medical.entity.ChronicExpense;
import com.groot.medical.entity.ChronicPattern;
import com.groot.medical.entity.ChronicPolicy;
import com.groot.medical.entity.PersonalFiles;
import com.groot.medical.service.ChronicExpenseService;
import com.groot.medical.service.ChronicExpenseServiceImpl;
import com.groot.medical.service.ChronicPatternService;
import com.groot.medical.service.ChronicPatternServiceImpl;
import com.groot.medical.service.ChronicPolicyService;
import com.groot.medical.service.ChronicPolicyServiceImpl;
import com.groot.medical.service.ChronicService;
import com.groot.medical.service.ChronicServiceImpl;
import com.groot.medical.service.PayService;
import com.groot.medical.service.PayServiceImpl;
import com.groot.medical.service.PersonalFileService;
import com.groot.medical.service.PersonalFileServiceImpl;

@WebServlet("/sys/expense.do")
public class ChronicExpenseController extends BaseServletController{
	private static final long serialVersionUID = 1L;
	private ChronicPatternService chronicPatternService = new ChronicPatternServiceImpl();
	private ChronicService chroniceService = new ChronicServiceImpl();
	private ChronicExpenseService chronicExpenseService = new ChronicExpenseServiceImpl();
	private PersonalFileService personalFileService = new PersonalFileServiceImpl();
	private PayService payService = new PayServiceImpl();
	private ChronicPolicyService chronicPolicyService = new ChronicPolicyServiceImpl();
	private static Logger LOGGER = Logger.getLogger(ChronicExpenseController.class);
	
	Date now = new Date();
	SimpleDateFormat year = new SimpleDateFormat("yyyy");//设置日期格式
	String nowTime = year.format(now);
	public String execute(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		LOGGER.info("this is @WebServlet(\"/index.do\").execute()");
		return null;
	}
	/**
	 * 打开身份证号输入页面
	 * @param request
	 * @param response
	 * @return
	 * @throws ServletException
	 * @throws IOException
	 */
	public String openCheckInfoPage(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setAttribute("tgId",request.getParameter("tgId"));
		return "/WEB-INF/page/expense/idcard_input.jsp";
	}
	/**
	 * 补全身份信息根据身份证号
	 * @param request
	 * @param response
	 * @return
	 * @throws ServletException
	 * @throws IOException
	 */
	public void findPersonInfoByIdCardNum (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String idCardNum = request.getParameter("idCardNum");
		System.out.println(idCardNum);
		List<PersonalFiles> psersons = chronicExpenseService.findPersonByIdCardNum(idCardNum);
		System.out.println("阿鲁啊："+psersons);
		Gson gson = new Gson();
		
        String str=gson.toJson(psersons);
        System.out.println("你好啊:::"+str);
        /*response.setContentType("text/html;charset=utf-8");*/
        ServletOutputStream outputStream = response.getOutputStream();
       
        outputStream.write((str.getBytes(Charset.forName("utf-8")))); //将json数据写入流中  
        outputStream.flush(); 
        outputStream.close();	
	}
	/**
	 * 根据身份证号检查用户是否参合
	 * @param request
	 * @param response
	 * @return
	 * @throws ServletException
	 * @throws IOException
	 */
	public String checkPersonInfoByIdCardNumber(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String idCardNum = request.getParameter("idCardNum");
		Date now = new Date();
		SimpleDateFormat year = new SimpleDateFormat("yyyy");//设置日期格式
		String nowTime = year.format(now);
		//根据身份证号检验用户是否参合（根据参合缴费登记表）
		boolean flage =  payService.findPersonInfoByIdAndYear(idCardNum,nowTime);
		System.out.println(flage);
		if(flage){
			//查询参合农民基本信息
			PersonalFiles person=personalFileService.findPersonInfoById(idCardNum);
			//查询慢性病类型
			List<ChronicDisease> chronicInfos=chroniceService.findAllChronicInfo();
			//查询用户所患慢性病名称
			ChronicPattern pattern = chronicPatternService.findChronicInfoByIdCardNum(idCardNum);
			request.setAttribute("person", person);
			request.setAttribute("pattern", pattern);
			request.setAttribute("chronicInfos", chronicInfos);
			return "/WEB-INF/page/expense/expense_add.jsp";
		}else{
			request.setAttribute("flag", "<script type='text/javascript'>alert('当前年度没有参合缴费');</script>");
			return "/WEB-INF/page/expense/idcard_input.jsp";
		}
	}
	/**
	 * 检查慢性病证信息与报销信息是否一致
	 * @param request
	 * @param response
	 * @return
	 * @throws ServletException
	 * @throws IOException
	 */
	public String checkPatternInfo(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		String illName = request.getParameter("illName");
		String name = request.getParameter("name");
		String idcardNumber = request.getParameter("idcardNumber");
		String farmingcardCode = request.getParameter("farmingcardCode");
		String medicalPays = request.getParameter("medicalPays");
		String hospitalpaycode = request.getParameter("hospitalpaycode");
		String hospitaltime = request.getParameter("hospitaltime");
		//查询参合农民基本信息
		PersonalFiles person=personalFileService.findPersonInfoById(idcardNumber);
		//查询慢性病类型
		List<ChronicDisease> chronicInfos=chroniceService.findAllChronicInfo();
		//查询用户所患慢性病名称
		ChronicPattern pattern = chronicPatternService.findChronicInfoByIdCardNum(idcardNumber);
		boolean flag=false;
		//1.检验慢性病证是否存在
		flag = chronicPatternService.checkPatternIsExistByIdCardNum(idcardNumber);
		if(flag){
			//2.判断慢性病名称是否一致
			flag = chronicPatternService.checkChronicNameIsEquals(idcardNumber,illName);
			if(flag){
				//3.判断是否过期
				flag = chronicPatternService.checkDateIsOut(idcardNumber,hospitaltime);
				if(flag){
					System.out.println("存在3");
					request.setAttribute("illName", illName);
					request.setAttribute("name", name);
					request.setAttribute("idcardNumber", idcardNumber);
					request.setAttribute("farmingcardCode", farmingcardCode);
					request.setAttribute("medicalPays", medicalPays);			
					request.setAttribute("hospitalpaycode", hospitalpaycode);			
					request.setAttribute("medicalPays", medicalPays);			
					return "/WEB-INF/page/expense/expense_show.jsp";
				}else{
					request.setAttribute("person", person);
					request.setAttribute("chronicInfos", chronicInfos);
					request.setAttribute("pattern", pattern);
					request.setAttribute("flag", "<script type='text/javascript'>alert('慢性病证过期');</script>");
					return "/WEB-INF/page/expense/expense_add.jsp";
				}
				
			}else{
				request.setAttribute("person", person);
				request.setAttribute("chronicInfos", chronicInfos);
				request.setAttribute("pattern", pattern);
				request.setAttribute("flag", "<script type='text/javascript'>alert('慢性病证疾病与 报销疾病不一致');</script>");
				return "/WEB-INF/page/expense/expense_add.jsp";
			}
			
		}else {
			request.setAttribute("person", person);
			request.setAttribute("chronicInfos", chronicInfos);
			request.setAttribute("pattern", pattern);
			request.setAttribute("flag", "<script type='text/javascript'>alert('不能查询到慢性病证');</script>");
			return "/WEB-INF/page/expense/expense_add.jsp";
			
		}
		
	}
	/**
	 * 报销本次慢性病金额
	 * @param request
	 * @param response
	 * @return
	 * @throws ServletException
	 * @throws IOException
	 */
	public String expenseMoney(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String illName = request.getParameter("illName");
		String name = request.getParameter("name");
		String idcardNumber = request.getParameter("idcardNumber");
		String farmingcardCode = request.getParameter("farmingcardCode");
		String medicalPays = request.getParameter("medicalPays");
		//查询当前年度的慢性病政策信息
		ChronicPolicy policy=chronicPolicyService.findChronicPolicyInfoByYear(nowTime);
		//-------------封顶线-------------------------------
		double AllMoeny=Double.parseDouble(policy.getMoney());
		//-------------报销率-------------------------------
		float scale=policy.getScale();
		//-------------已报销金额--------------------------查询当前年度该用户已报销金额(身份证号+年份)
		double alreadyMoeny=chronicExpenseService.findAlreadyExpenseMoeny(idcardNumber,nowTime);
		//-------------剩余可报销金额------------------------
		double surplusMoney=AllMoeny-alreadyMoeny;
		//-------------预报销金额----------------------------
		DecimalFormat df = new DecimalFormat("#########.##");
		String wantMoney = df.format(Float.parseFloat(medicalPays)*scale);
		//-------------报销后所需支付金额---------------------
		double afterMoeny=0;
		//如果剩余可报销金额小于本次想要报销金额（那么本年度就报销完了）
		if(surplusMoney>Double.parseDouble(wantMoney)){
			afterMoeny=Double.parseDouble(medicalPays)-Double.parseDouble(wantMoney);
		}else{
			afterMoeny=Double.parseDouble(medicalPays)-surplusMoney;
		}
		//-------------本次报销金额---------------------------
		double thisMoeny = Double.parseDouble(medicalPays)-afterMoeny;
		//根据报销金额=（（封顶线-年度已报销金额）>=预报销金额）
		//1.判断是否还能报销（本次报销超出了封顶线)
		if(alreadyMoeny>=AllMoeny){
			request.setAttribute("flag", "<script type='text/javascript'>alert('您今年的报销额度已经用完');</script>");
			return "/WEB-INF/page/expense/idcard_input.jsp";
		}else{
			//计算本次报销金额
				//可以报销
				System.out.println("可以报销!!!!!");
				System.out.println((AllMoeny-alreadyMoeny)-Double.parseDouble(wantMoney));
				//生产发票号
				String ticket = TicketUtil.getDefaultFapiao();
				request.setAttribute("surplusMoney", surplusMoney);
				request.setAttribute("alreadyMoeny", alreadyMoeny);
				request.setAttribute("illName", illName);
				request.setAttribute("name", name);
				request.setAttribute("idcardNumber", idcardNumber);
				request.setAttribute("farmingcardCode", farmingcardCode);
				request.setAttribute("afterMoeny", afterMoeny);
				request.setAttribute("thisMoeny", thisMoeny);
				request.setAttribute("medicalPays", Double.parseDouble(medicalPays));
				request.setAttribute("ticket", ticket);
				request.setAttribute("date", SimpleDateUtil.now());
				return "/WEB-INF/page/expense/this_expense_info.jsp";
			}
	}
	
	/**
	 * 确定支付
	 * @param request
	 * @param response
	 * @return
	 * @throws ServletException
	 * @throws IOException
	 */
	public String defineExpnseMoney(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String thisMoeny = request.getParameter("thisMoeny");
		String ticket = request.getParameter("ticket");
		String illName = request.getParameter("illName");
		String idcardNumber = request.getParameter("idcardNumber");
		String farmingcardCode = request.getParameter("farmingcardCode");
		ChronicExpense expense = new ChronicExpense();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 
         try {
            Date dt = sdf.parse(SimpleDateUtil.now());
            expense.setExpenseTime(new Timestamp(dt.getTime()));
        } catch (ParseException e) {
            e.printStackTrace();
        }

		//封装数据
		
		expense.setIdCardNumber(idcardNumber);
		expense.setFarmingCardCode(farmingcardCode);
		expense.setIllCode(illName);
		expense.setTicketCode(ticket);
		expense.setCurrentYear(nowTime);
		expense.setHospitalTicket("119");
		expense.setExpenseMoney(Double.parseDouble(thisMoeny));
		expense.setIsPass(0);
		expense.setIsRemittance(0);
		chronicExpenseService.defineExpenseMoney(expense);
		request.setAttribute("flag", "<script type='text/javascript'>alert('报销成功');</script>");
		return openCheckInfoPage(request,response);
	}
}
